<template>
  <div class="app-container org">
    <el-card class="leftCard">
      <!-- 搜索条件盒子 -->
      <div>
        <p class="pinformation">搜索条件</p>
        <el-form :model="queryParams" ref="queryRef" label-width="80px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="包名称：" prop="packageName">
                <el-input
                  v-model.trim="queryParams.packageName"
                  placeholder="请输入包名称"
                  maxlength="100"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="13">
              <el-form-item label="检测类别：" prop="jclbId">
                <el-select
                  v-model="queryParams.jclbId"
                  placeholder="请选择检测类别"
                  clearable
                  @change="handleQuery"
                  filterable
                >
                  <el-option
                    v-for="item in proxy.addListNoLimit(
                      detectionTypeList,
                      'jclbId',
                      'jclbName'
                    )"
                    :key="item.jclbId"
                    :label="item.jclbName"
                    :value="item.jclbId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-row justify="end">
                <el-button type="success" @click="handleQuery">搜索</el-button>
                <el-button class="business resetBtn" @click="resetQuery">重置</el-button>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div>
        <el-row style="justify-content: space-between">
          <el-row>
            <p class="pinformation">项目方法包列表</p>
            <p class="totalStyle">共 {{ total }} 条数据</p>
          </el-row>
          <el-row style="padding-bottom: 4px">
            <el-button type="success" link icon="Plus" @click="handleAdd">新增</el-button>
            <el-button
              type="success"
              link
              icon="Delete"
              @click="handleDelete"
              :disabled="multiple > 0 ? false : true"
              >删除</el-button
            >
          </el-row>
        </el-row>

        <el-table
          class="business"
          v-loading="loading"
          :data="packageTable"
          :row-class-name="tableRowClass"
          @row-click="rowClick"
          @selection-change="handleSelectionChange"
          ref="mainTableRef"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="项目方法包名称" align="center" prop="packageName" />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button link type="success" @click.stop="handleCopy(scope.row)"
                >复制</el-button
              >
              <el-button link type="success" @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </el-card>

    <el-card class="rightCard">
      <!-- 基础信息 -->
      <el-form label-width="130px" :model="form" :rules="rules" ref="packageRef">
        <div>
          <el-row style="margin-bottom: 5px">
            <el-col :span="22">
              <p class="pinformation">基础信息</p>
            </el-col>
            <el-col :span="2">
              <el-button type="success" size="small" @click="submitForm">保存</el-button>
            </el-col>
          </el-row>
          <el-row></el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item label="项目方法包名称：" prop="packageName">
                <el-input
                  v-model="form.packageName"
                  maxlength="20"
                  placeholder="请输入包名"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检测类别：" prop="jclbId">
                <el-select v-model="form.jclbId" placeholder="请选择检测类别" filterable>
                  <el-option
                    v-for="(item, index) in detectionTypeList"
                    :key="item.jclbId"
                    :label="item.jclbName"
                    :value="item.jclbId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row></el-row>
        </div>
      </el-form>
      <!-- /搜索检测项目 -->

      <!-- 搜索结果 -->
      <div>
        <el-row style="margin-top: 10px; !important">
          <el-row>
            <p class="pinformation">检测项目列表</p>
            <p class="totalStyle">共 {{ jcxmTotal }} 条数据</p>
          </el-row>
          <el-row style="padding-bottom: 4px">
            <el-button
              type="success"
              link
              @click="handleSelectJcxm"
              :disabled="!form.packageId"
              icon="Search"
              style="margin-left: 15px"
            >
              选择检测项目
            </el-button>

            <el-button
              class="deleteBtnColor"
              link
              @click="massDeleteBtnClick"
              icon="CircleClose"
              style="margin-left: 15px"
            >
              批量删除
            </el-button>
          </el-row>
        </el-row>
        <el-table
          :data="selectedJcxmList"
          ref="buttomTableRef"
          v-loading="selectedJcxmListLoading"
          @selection-change="onDeleteSelect"
          row-key="mJId"
          border
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="检测项目名称" prop="jcxmName" align="left" width="170">
            <template #default="scope">
              <span v-html="transformation(scope.row.jcxmName)"></span>
            </template>
          </el-table-column>
          <el-table-column label="方法编号" prop="methodCode" align="center" width="150">
            <template #default="scope">
              <div v-if="scope.row.b">{{ scope.row.methodCode }}</div>
              <div v-if="scope.row.a">
                <el-select
                  v-model="scope.row.methodCode"
                  clearable
                  filterable
                  remote
                  reserve-keyword
                  remote-show-suffix
                  @click="getJcxmId(scope.row)"
                  :remote-method="remoteMethod"
                  :loading="loading_1"
                  @change="selectChange(scope.row.methodCode, scope.$index)"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in jcxmList"
                    :key="item.methodId"
                    :label="item.methodCode + '　' + item.methodName"
                    :value="item.methodId"
                  >
                    <el-tooltip
                      class="box-item"
                      effect="customized"
                      placement="right"
                      :content="item.methodCode + '　' + item.methodName"
                    >
                      <div
                        style="
                          white-space: nowrap;
                          overflow: hidden;
                          text-overflow: ellipsis;
                        "
                      >
                        {{ item.methodCode + "　" + item.methodName }}
                      </div>
                    </el-tooltip>
                  </el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="方法名称" align="center">
            <template #default="scope">
              <span v-html="transformation(scope.row.methodName)"></span>
            </template>
          </el-table-column>
          <el-table-column label="是否求和" align="center" width="100">
            <template #default="scope">
              <span v-if="scope.row.children">{{
                scope.row.isSum == 0 ? "否" : "是"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="120"
          >
            <template #default="scope">
              <el-button
                link
                type="success"
                icon="Delete"
                @click="handleListDelete(scope)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <jcxmDialog
      ref="jcxmDialogRef"
      :jclbId="form.jclbId"
      v-if="jcxmDialogShow"
      @dialogClose="handleSelectedList"
    />
  </div>
</template>

<script setup name="Package">
import {
  listPackage,
  addPackage,
  listRightPackage,
  seletedJcxmList,
  getPackage,
  delPackage,
  copyPackage,
  delPackageJcxm
} from "@/api/store/package";
import { allListJclb } from "@/api/store/jclb";
import { onMounted } from "vue";
import jcxmDialog from "./dialogJcxm.vue";

const { proxy } = getCurrentInstance();
const { lims_jcxm_group } = proxy.useShareDict("lims_jcxm_group");
const jcxmDialogShow = ref(false);
const selectedJcxmListLoading = ref(false);
const loading = ref(true);
const ids = ref([]);
const multiple = ref(false);
const total = ref(0);
const jcxmTotal = ref(0);
const packageTable = ref([]); // 项目方法包表格列表数据
const detectionTypeList = ref([]); // 检测类别列表数据
const selectedJcxmList = ref([]); // 右侧检测项目方法包表格数据

// 获取检测类别列表数据
function getJclbTypeList() {
  allListJclb().then((res) => {
    detectionTypeList.value = res.data;
  });
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1, // 当前页数
    pageSize: 10, // 当前页数据条数
    packageName: null, // 项目方法包名称
    jclbId: -1, // 检测类别ID
  },
  // 表单校验规则
  rules: {
    packageName: [{ required: true, message: "包名不能为空", trigger: "blur" }],
    jclbId: [{ required: true, message: "检测类别不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询项目方法包列表 */
function getList() {
  loading.value = true;
  listPackage(queryParams.value).then((response) => {
    packageTable.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 表单重置
function reset() {
  selectedJcxmList.value = [];
  form.value = {};
  jcxmTotal.value = 0;
  proxy.$refs["packageRef"].clearValidate();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.packageId);
  multiple.value = selection?.length;
}

const tempIds = ref([]);

function rowClick(row) {
  return new Promise((resolve, reject) => {
    reset();
    getPackage(row.packageId).then(async (response) => {
      form.value = response.data;
      heightBright.value = row.packageId;
      resolve();
      heightBright.value = row.packageId;
      handleSelectedList();
    });
  });
}

function handleSelectedList(dialog) {
  if (dialog) {
    jcxmDialogShow.value = false;
  }
  if (!dialog || dialog == 1) {
    //dialog:null为进入页面时调用 1：弹出重新选择检测项目调用。
    seletedJcxmList(form.value.packageId).then(async (response) => {
      selectedJcxmList.value = response.data;
      let count = 0;
      selectedJcxmList.value.forEach((item) => {
        if (item.children) {
          count += item.children.length;
        } else {
          count++;
        }
      });
      jcxmTotal.value = count;
    });
  }
}
function handleCopy(row) {
  proxy.$modal.confirm("确认要复制当前选择的项目方法包吗？").then(function () {
    copyPackage(row.packageId).then((res) => {
      proxy.$modal.msgSuccess("复制成功");
      rowClick({ packageId: res.data }).then(() => {});
    });
  });
}

const jcxmList = ref([]);
const handleListEditor = (row, index) => {
  row.a = true;
  row.b = false;
  selectedJcxmList.value[index] = JSON.parse(JSON.stringify(row));
  // listRightPackage({ jcxmId: row.jcxmId, jclbId: form.value.jclbId }).then(
  //   (res) => {
  //     jcxmList.value = res.data;
  //   }
  // );
};
const handleListSave = (row) => {
  row.a = false;
  row.b = true;
};

function handleListDelete(scope) {
  proxy.$modal
    .confirm("是否确认删除该条检测项目？")
    .then(function () {
      return delPackageJcxm(form.value.packageId,[scope.row.mJId])
    })
    .then(() => {
      proxy.$modal.msgSuccess("删除成功");
      handleSelectedList();
    })
    .catch(() => {});
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["packageRef"].validate((valid) => {
    if (valid) {
      addPackage(form.value).then((res) => {
        if (form.value.packageId) {
          proxy.$modal.msgSuccess("编辑成功");
          getList();
        } else {
          form.value.packageId = res.data;
          proxy.$modal.msgSuccess("新增成功");
          heightBright.value = res.data;
          resetQuery();
        }
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _packageIds = row.packageId || ids.value;
  proxy.$modal
    .confirm("删除该项目方法包将删除其所有详细信息数据，确定删除吗？")
    .then(function () {
      return delPackage(_packageIds);
    })
    .then(() => {
      getList();
      handleAdd();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 添加按钮操作 */
function handleAdd() {
  reset();
  proxy.$refs["packageRef"].clearValidate();
  heightBright.value = "";
}

const selectIds = ref([]);
// 拿到选中行
const onDeleteSelect = (deleteRows) => {
  // 拿到选中的主键根据主键去进行批量删除 selectIds.value 里面是选中的主键 id
  selectIds.value = deleteRows.map((item) => {
    return item.mJId;
  });
};
// 点击批量删除按钮
const massDeleteBtnClick = () => {
  if (selectIds.value?.length > 0) {
    proxy.$modal
      .confirm("是否确认删除选中的检测项目？")
      .then(function () {
        return delPackageJcxm(form.value.packageId,selectIds.value)
      })
      .then(() => {
        proxy.$modal.msgSuccess("删除成功");
        handleSelectedList();
      })
      .catch(() => {});
  }
};

getList();

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [
        { tableName: "main", bottomHeight: 73 },
        { tableName: "sub", bottomHeight: 400 },
        { tableName: "buttom", bottomHeight: 22 },
      ];
    } else {
      heightParams.value = [
        { tableName: "main", bottomHeight: 21 },
        { tableName: "sub", bottomHeight: 400 },
        { tableName: "buttom", bottomHeight: 22 },
      ];
    }
    getTableHeight();
  }
);

// 自适应样式
const heightParams = ref([
  { tableName: "main", bottomHeight: 21 },
  { tableName: "sub", bottomHeight: 400 },
  { tableName: "buttom", bottomHeight: 22 },
]);
function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}

onMounted(() => {
  nextTick(function () {
    getTableHeight();
    getJclbTypeList(); //获取检测类别列表数据
    window.addEventListener("resize", getTableHeight);
  });
});

onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

function selectChange(row, index) {
  jcxmList.value?.forEach((item, index1) => {
    if (item.methodId == row) {
      selectedJcxmList.value[index] = jcxmList.value[index1];
      selectedJcxmList.value[index].a = true;
      selectedJcxmList.value[index].b = false;
      jcxmList.value[index1] = JSON.parse(JSON.stringify(item));
    }
  });
}

const heightBright = ref("");
function tableRowClass({ row }) {
  if (row) {
    if (row.packageId == heightBright.value) {
      return "current-row";
    }
    return "";
  }
}

function transformation(row) {
  const a = proxy.getSupAndSub(row);
  return a;
}

const loading_1 = ref(false);
const jcxmId = ref("");

function getJcxmId(row) {
  jcxmId.value = row.jcxmId;
}

function remoteMethod(val) {
  if (val) {
    loading_1.value = true;
    setTimeout(() => {
      listRightPackage({
        jcxmId: jcxmId.value,
        jclbId: form.value.jclbId,
        methodCode: val,
      }).then((res) => {
        loading_1.value = false;
        jcxmList.value = res.rows;
      });
    }, 200);
  } else {
    jcxmList.value = [];
  }
}

function handleSelectJcxm() {
  jcxmDialogShow.value = true;
  nextTick(() => {
    // 打开新增/编辑检测方法dialog
    proxy.$refs["jcxmDialogRef"].isShowDialog = true;
    form.value.jclbName = proxy.getItemByArray(
      detectionTypeList.value,
      "jclbId",
      form.value.jclbId,
      "jclbName"
    );
    proxy.$refs["jcxmDialogRef"].setParams(form.value);
  });
}
</script>

<style>
.el-button.is-link.deleteBtnColor {
  color: red !important;
}
</style>
